package user

import (
	"context"
	"github.com/go-kit/kit/auth/jwt"
	"github.com/go-kit/kit/endpoint"
	"gysa-share01/common"
	"gysa-share01/exception"
	"gysa-share01/user-service/auth"
	service_user "gysa-share01/user-service/user/proto"
)

func MakeGrpcInfoEndpoint(service UserServiceInterface) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		infoReq, ok := request.(*service_user.InfoRequest)
		if !ok {
			err = exception.NewGeneralException("参数错误", exception.PARAMETER_ERROR)
			return
		}
		user, ok := ctx.Value(jwt.JWTClaimsContextKey).(*auth.AuthClaims)
		common.Logger.Printf("\nctx:%v\n", ctx)
		common.Logger.Printf("\nuser:%+v\n", user)

		userModel, err := service.Info(uint(infoReq.UserId))
		if err != nil {
			exc, ok := err.(exception.ExceptionInterface)
			if ok {
				response = &service_user.InfoResponse{
					ErrCode: int32(exc.ECode()),
					ErrMsg:  exc.Error(),
				}
				err = nil
			}

			return
		}

		response = &service_user.InfoResponse{
			ErrCode: 0,
			ErrMsg:  "",
			User: &service_user.UserInfo{
				ID:       uint64(userModel.ID),
				Username: userModel.Username,
				Money:    userModel.Money,
				Nickname: userModel.Nickname,
			},
		}

		return
	}
}
